/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.infor.web;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.fee.entity.Profit;
import com.jeeplus.modules.fee.service.ProfitService;
import com.jeeplus.modules.infor.entity.*;
import com.jeeplus.modules.infor.service.*;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;

/**
 * 仓租利润分析Controller
 * @author 李超辉
 * @version 2018-09-27
 */
@Controller
@RequestMapping(value = "${adminPath}/infor/rent")
public class RentController extends BaseController {

	@Autowired
	private RentService rentService;
	@Autowired
	private ProfitAnalysisService profitAnalysisService;
	@Autowired
	private JdbcTemplate jdbc;
	@Autowired
	private ProfitService profitService;
	@Autowired
	private RentPriceService rentPriceService;
	@Autowired
	private PositionService positionService;
	@Autowired
	private LoadingBottomService loadingBottomService;
	@Autowired
	private LoadingIncomeService loadingIncomeService;
	@Autowired
	private LoadingOutService loadingOutService;
	@ModelAttribute
	public Rent get(@RequestParam(required=false) String id) {
		Rent entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = rentService.get(id);
		}
		if (entity == null){
			entity = new Rent();
		}
		return entity;
	}
	/**
	 * 利润分析总表列表数据
	 */
	@ResponseBody
	@RequestMapping(value = "cx")
	public String cx(Date min, Date max, String pro) {
		jdbc.execute("delete from infor_rent");
		Calendar c = Calendar.getInstance();
		DecimalFormat df = new DecimalFormat("0.00%");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		NumberFormat nf = NumberFormat.getInstance();
		Date i=min;
		Date mixx;
		Date maxx;
		while (i.getTime()<max.getTime()) {
			mixx=i;
			Rent rent=new Rent();
			rent.setDate(i);
			c.setTime(i);
			c.add(Calendar.MONTH, 1);
			i=c.getTime();

			//仓租
			RentPrice r=new RentPrice();
			r.setMin(mixx);
			r.setMax(mixx);

			if(pro!=null &&!pro.equals("")&&!pro.equals("undefined")){
				r.setPro(pro);
			}else if(!UserUtils.getUseroffice().equals("总部")){
				r.setPro(UserUtils.getUseroffice());
			}
			List<RentPrice> lis=rentPriceService.findList(r);
			Double sr=0.0;
			Double zc=0.0;
			Double srhs=0.0;
			Double zchs=0.0;
			double area=0.0;
			for(RentPrice ren:lis){

				if(ren.getType().equals("收入")){
					area+=Double.parseDouble(ren.getArea());
					srhs+=(Double.parseDouble(ren.getPrice())*Double.parseDouble(ren.getAd()))*Double.parseDouble(ren.getArea())*(Double.parseDouble(ren.getSl())+1);
					sr+=(Double.parseDouble(ren.getPrice())*Double.parseDouble(ren.getAd()))*Double.parseDouble(ren.getArea());
				}else{
					zchs+=(Double.parseDouble(ren.getPrice())*Double.parseDouble(ren.getAd()))*Double.parseDouble(ren.getArea())*(Double.parseDouble(ren.getSl())+1);
					zc+=(Double.parseDouble(ren.getPrice())*Double.parseDouble(ren.getAd()))*Double.parseDouble(ren.getArea());
				}
			}
			rent.setSr(nf.format(sr).replaceAll(",",""));
			rent.setZc(nf.format(zc).replaceAll(",",""));
			rent.setSrhs(nf.format(srhs).replaceAll(",",""));
			rent.setZchs(nf.format(zchs).replaceAll(",",""));
			rent.setArea(nf.format(area).replaceAll(",",""));
			double mlr=srhs-zchs;
			rent.setMlr(nf.format(mlr).replaceAll(",",""));
			rent.setLrl(df.format(mlr/srhs));
			rentService.save(rent);
		}
		return "success";
	}
	/**
	 * 仓租利润分析列表页面
	 */
	@RequiresPermissions("infor:rent:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/infor/rentList";
	}
	
		/**
	 * 仓租利润分析列表数据
	 */
	@ResponseBody
	@RequiresPermissions("infor:rent:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Rent rent, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Rent> page = rentService.findPage(new Page<Rent>(request, response), rent); 
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑仓租利润分析表单页面
	 */
	@RequiresPermissions(value={"infor:rent:view","infor:rent:add","infor:rent:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Rent rent, Model model) {
		model.addAttribute("rent", rent);
		return "modules/infor/rentForm";
	}

	/**
	 * 保存仓租利润分析
	 */
	@ResponseBody
	@RequiresPermissions(value={"infor:rent:add","infor:rent:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(Rent rent, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, rent)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		rentService.save(rent);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存仓租利润分析成功");
		return j;
	}
	
	/**
	 * 删除仓租利润分析
	 */
	@ResponseBody
	@RequiresPermissions("infor:rent:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Rent rent, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		rentService.delete(rent);
		j.setMsg("删除仓租利润分析成功");
		return j;
	}
	
	/**
	 * 批量删除仓租利润分析
	 */
	@ResponseBody
	@RequiresPermissions("infor:rent:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			rentService.delete(rentService.get(id));
		}
		j.setMsg("删除仓租利润分析成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("infor:rent:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(Rent rent, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "仓租利润分析"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Rent> page = rentService.findPage(new Page<Rent>(request, response, -1), rent);
    		new ExportExcel("仓租利润分析", Rent.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出仓租利润分析记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("infor:rent:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Rent> list = ei.getDataList(Rent.class);
			for (Rent rent : list){
				try{
					rentService.save(rent);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条仓租利润分析记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条仓租利润分析记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入仓租利润分析失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/rent/?repage";
    }
	
	/**
	 * 下载导入仓租利润分析数据模板
	 */
	@RequiresPermissions("infor:rent:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "仓租利润分析数据导入模板.xlsx";
    		List<Rent> list = Lists.newArrayList(); 
    		new ExportExcel("仓租利润分析数据", Rent.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/rent/?repage";
    }

}